package com.kyzh.core.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.StateListDrawable
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.kyzh.core.MyApplication
import org.jetbrains.anko.dip
import java.lang.reflect.Field
import kotlin.math.abs


object ViewUtils {
    abstract class AppBarLayoutStateChangeListener : AppBarLayout.OnOffsetChangedListener {
        private var mCurrentState = State.INTERMEDIATE

        enum class State {
            EXPANDED, //展开
            COLLAPSED, //折叠
            INTERMEDIATE//中间状态
        }

        override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
            when {
                verticalOffset == 0 -> {
                    if (mCurrentState != State.EXPANDED) {
                        onStateChanged(appBarLayout, State.EXPANDED)
                    }
                    mCurrentState = State.EXPANDED
                }
                abs(verticalOffset) >= appBarLayout.totalScrollRange -> {
                    if (mCurrentState != State.COLLAPSED) {
                        onStateChanged(appBarLayout, State.COLLAPSED)
                    }
                    mCurrentState = State.COLLAPSED
                }
                else -> {
                    if (mCurrentState != State.INTERMEDIATE) {
                        onStateChanged(appBarLayout, State.INTERMEDIATE)
                    }
                    mCurrentState = State.INTERMEDIATE
                }
            }
        }

        abstract fun onStateChanged(appBarLayout: AppBarLayout, state: State)
    }
    /*设置布局高度*/
    fun setHeight(view: View, height: Int) {
        val pp = view.layoutParams
        pp.height = height
        view.layoutParams = pp
    }
    /*设置布局宽度度*/
    fun setWidth(view: View, width: Int) {
        val pp = view.layoutParams
        pp.width = width
        view.layoutParams = pp
    }
    fun getPx(context: Context, dp: Int): Int {
        val newPx: Int
        val dm = context.resources.displayMetrics
        val screenWidth = dm.densityDpi
        newPx = when {
            (screenWidth <= 500) and (screenWidth >= 400) -> dp *3
            (screenWidth <= 350) and (screenWidth >= 300) -> dp* 2
            (screenWidth >= 600) and (screenWidth <= 660) -> dp * 4
            else -> dp*3
        }
        return newPx
    }

    /*动态获取状态栏高度*/
    fun getStateBarHeight(context: Context): Int {
        var statusBarHeight = 0
        val res = context.resources
        val resourceId = res.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            statusBarHeight = res.getDimensionPixelSize(resourceId)
        }
        return statusBarHeight
    }
    /*动态设置margin*/
    fun setMargins(v: View, l: Int, t: Int, r: Int, b: Int) {
        if (v.layoutParams is ViewGroup.MarginLayoutParams) {
            val p = v.layoutParams as ViewGroup.MarginLayoutParams
            p.setMargins(l, t, r, b)
            v.layoutParams = p
        }
    }
    fun getBitmapFromVectorDrawable(context: Context, drawableId: Int): Bitmap {
        var drawable = ContextCompat.getDrawable(context, drawableId)!!
        drawable = DrawableCompat.wrap(drawable).mutate()
        val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight())
        drawable.draw(canvas)
        return bitmap
    }

    val Int.dp : Int
    get() {
        return MyApplication.instance.dip(this)
    }


    fun TabLayout.setIndicator( leftDip: Float, rightDip: Float) {
            try {
                val slidingTabIndicatorField: Field
                var textViewField: Field
                // 拿到tabLayout的slidingTabIndicator属性
                slidingTabIndicatorField =
                    javaClass.getDeclaredField("tabSelectedIndicator")
                slidingTabIndicatorField.isAccessible = true
                val mTabStrip = slidingTabIndicatorField[this] as StateListDrawable
                mTabStrip.setBounds(0,0,5,10)
                invalidate()
                Log.e("TAG", "setIndicator: ", )
            } catch (e: NoSuchFieldException) {
                e.printStackTrace()
                Log.e("TAG",e.localizedMessage )
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
                Log.e("TAG",e.localizedMessage )
            }

    }

    fun changeTabIndicatorWidth(tabLayout: TabLayout, margin: Int) {
        tabLayout.post {
            try {
                val mTabStripField = tabLayout.javaClass.getDeclaredField("mTabStrip")
                mTabStripField.isAccessible = true
                val mTabStrip = mTabStripField[tabLayout] as LinearLayout
                val dp10 = if (margin == 0) 50 else margin
                for (i in 0 until mTabStrip.childCount) {
                    val tabView = mTabStrip.getChildAt(i)
                    val mTextViewField = tabView.javaClass.getDeclaredField("mTextView")
                    mTextViewField.isAccessible = true
                    val mTextView = mTextViewField[tabView] as TextView
                    tabView.setPadding(0, 0, 0, 0)
                    var width = 0
                    width = mTextView.width
                    if (width == 0) {
                        mTextView.measure(0, 0)
                        width = mTextView.measuredWidth
                    }
                    val params = tabView.layoutParams as LinearLayout.LayoutParams
                    params.width = 20
                    params.leftMargin = dp10
                    params.rightMargin = dp10
                    tabView.layoutParams = params
                    tabView.invalidate()
                }
            } catch (e: NoSuchFieldException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }
    }
//    fun View.navClick(nav: Nav){
//        setOnClickListener {
//            if (nav.login == 1){
//                if (uid.isBlank()){
//                    this.context.startActivity<LoginActivity>()
//                    return@setOnClickListener
//                }
//            }
//            if (nav.url.isNotBlank()){
//                if(nav.type ==  314 ){
//                    context.startActivity<CouponActivity>()
//                }else
//                startBrowser(nav.url,nav.name)
//            }else{
//                when(nav.type){
//                    311-> context.startActivity<BaseFragmentActivity>(GlobalKeys.TYPE to BaseFragmentActivity.GIFT)
//                    314-> context.startActivity<CouponActivity>()
//                    320-> startBrowser("${BASEURLV1}/?ct=app&ac=renwu&uid=${SpConsts.uid}&t=${time}&sign=${httpSign(SpConsts.uid)}&type=1",nav.name)
//                    323-> context.startActivity<PointsMallActivity>()
//                    324-> context.startActivity<TaskCenterActivity>()
//                    325-> context.startActivity<BaseFragmentActivity>(GlobalKeys.TYPE to BaseFragmentActivity.DEAL)
//                    326-> startBrowser("${Base.BASEURL}/?ct=h5apppay&uid=${SpConsts.uid}","平台币充值")
//                    327-> startBrowser("${Base.BASEURL}/?ct=app&ac=shenqing&uid=${SpConsts.uid}&t=${time}&sign=${httpSign(SpConsts.uid)}","返利申请")
//                }
//            }
//        }
//    }
}